package com.hzeport.bgs22emduty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.entity.BaseDeptInfo;
import com.hzeport.bgs22emduty.entity.BasePersonInfo;
import com.hzeport.bgs22emduty.entity.ParamHolidays;
import com.hzeport.bgs22emduty.entity.ParamLeader;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.outbound.BaseDeptInfoRepository;
import com.hzeport.bgs22emduty.outbound.BasePersonInfoRepository;
import com.hzeport.bgs22emduty.outbound.ParamLeaderRepository;
import com.hzeport.bgs22emduty.outbound.db.ParamHolidaysRepositoryImpl;
import com.hzeport.bgs22emduty.outbound.db.ParamLeaderRepositoryImpl;
import com.hzeport.bgs22emduty.service.ParamHolidaysService;
import com.hzeport.bgs22emduty.service.ParamLeaderService;
import com.hzeport.bgs22emduty.vo.ParamDuty.ParamDutyListVO;
import com.hzeport.bgs22emduty.vo.ParamLeader.ParamLeaderListVO;
import com.hzeport.bgs22emduty.vo.ParamLeader.ParamLeaderSaveVO;
import com.hzeport.bgs22emduty.vo.ParamLeader.ParamLeaderdetailVO;
import com.hzeport.bgs22emduty.vo.base.PageVO;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author hzeport
 */
@Service
@Slf4j
public class ParamLeaderServiceImpl extends BaseServiceImpl<ParamLeaderRepositoryImpl, ParamLeader> implements ParamLeaderService {

    @Resource
    private ParamLeaderRepository paramLeaderRepository;
    @Resource
    private BaseDeptInfoRepository baseDeptInfoRepository;
    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;
    @Override
    public BaseResult<Page<ParamLeaderListVO>> list(PageVO pageVO, UserInfoDetailVO userInfo) {
        Page<ParamLeader> page=new Page<>();
//        if (userInfo.getRole()!=null&&userInfo.getRole().contains("SYSTEM_ADMIN")){
//             page = paramLeaderRepository.page(new Page(pageVO.getPageNum(),pageVO.getPageSize()),
//                    new LambdaQueryWrapper<ParamLeader>());
//        }
//        else {
            String id=userInfo.getCustomscode();
             page = paramLeaderRepository.page(new Page(pageVO.getPageNum(),pageVO.getPageSize()),
                    new LambdaQueryWrapper<ParamLeader>().eq(ParamLeader::getDeptId,id));
//        }
        List<ParamLeaderListVO> paramLeaderListVOPage=new ArrayList<>();
        for (ParamLeader paramLeader : page.getRecords()) {
            ParamLeaderListVO paramLeaderListVO = new ParamLeaderListVO();
            BeanUtils.copyProperties(paramLeader,paramLeaderListVO);
            paramLeaderListVO.setDate(paramLeader.getSYear()+"-"+paramLeader.getSMonth());
            List<BasePersonInfo> personInfo= basePersonInfoRepository.list(
                    new LambdaQueryWrapper<BasePersonInfo>().eq(BasePersonInfo::getUserno,paramLeader.getLeaderCode()));
            BasePersonInfo tempBasePerson=personInfo.stream().filter(i->"0".equals(i.getSideLine()))
                    .findAny().orElse(null);
            if (tempBasePerson==null){
                tempBasePerson=personInfo.get(0);
            }
            if(CollectionUtils.isEmpty(personInfo)){
                paramLeaderListVO.setUsername("");
                paramLeaderListVO.setUserno("");
                paramLeaderListVO.setDeptName("");
            }else {
                paramLeaderListVO.setUsername(tempBasePerson.getUsername());
                paramLeaderListVO.setUserno(tempBasePerson.getPhoneShort());
                BaseDeptInfo baseDeptInfo=baseDeptInfoRepository.getById(tempBasePerson.getDeptId());
                if(Objects.isNull(baseDeptInfo)){
                    paramLeaderListVO.setDeptName("");
                }else {
                    paramLeaderListVO.setDeptName(baseDeptInfo.getDeptName());
                }
            }
            paramLeaderListVOPage.add(paramLeaderListVO);
        }
//        List<ParamLeaderListVO> paramLeaderListVOPage = page.getRecords().stream().map(i->{
//            ParamLeaderListVO paramLeaderListVO = new ParamLeaderListVO();
//            BeanUtils.copyProperties(i,paramLeaderListVO);
//            paramLeaderListVO.setDate(i.getSYear()+"-"+i.getSMonth());
//            //工号查询人员信息
//            List<BasePersonInfo> personInfo= basePersonInfoRepository.list(
//                    new LambdaQueryWrapper<BasePersonInfo>().eq(BasePersonInfo::getUserno,i.getLeaderCode()));
//            if(CollectionUtils.isEmpty(personInfo)){
//                paramLeaderListVO.setUsername("");
//                paramLeaderListVO.setUserno("");
//                paramLeaderListVO.setDeptName("");
//            }else {
//                paramLeaderListVO.setUsername(personInfo.get(0).getUsername());
//                paramLeaderListVO.setUserno(personInfo.get(0).getPhoneShort());
//                BaseDeptInfo baseDeptInfo=baseDeptInfoRepository.getById(personInfo.get(0).getDeptId());
//                if(Objects.isNull(baseDeptInfo)){
//                    paramLeaderListVO.setDeptName("");
//                }else {
//                    paramLeaderListVO.setDeptName(baseDeptInfo.getDeptName());
//                }
//            }
//            return paramLeaderListVO;
//        }).collect(Collectors.toList());
        Page<ParamLeaderListVO> listVOPage = new Page<>();
        listVOPage.setRecords(paramLeaderListVOPage);
        listVOPage.setTotal(page.getTotal());
        return BaseResult.ok(listVOPage,"查询成功");
    }

    @Override
    public BaseResult<ParamLeaderdetailVO> detail(String id) {
        ParamLeader leader = paramLeaderRepository.getById(id);
        ParamLeaderdetailVO paramLeaderdetailVO = new ParamLeaderdetailVO();
        BeanUtils.copyProperties(leader,paramLeaderdetailVO);
//        if(leader.getSMonth() < 10){
//            paramLeaderdetailVO.setDate(LocalDate.parse(leader.getSYear()+"-"+"0"+leader.getSMonth()+"-01"));
//        }else {
//            paramLeaderdetailVO.setDate(LocalDate.parse(leader.getSYear()+"-"+leader.getSMonth()+"-01"));
//        }
        return BaseResult.ok(paramLeaderdetailVO,"获取详情成功");
    }
    @Override
    @Transactional(rollbackFor = Exception .class)
    public BaseResult saveData(ParamLeaderSaveVO paramHolidaysSaveVO, UserInfoDetailVO userInfo) throws Exception {
//        if("2".equals(paramHolidaysSaveVO.getLeaderName())&&!("海关总署".equals(paramHolidaysSaveVO.getCustomName())||"钱江海关".equals(paramHolidaysSaveVO.getCustomName()))){
//            throw new Exception("非杭州、钱江关区只可设置一个处领导作为带班领导");
//        }
        ParamLeader paramLeader = new ParamLeader();
       // String[] tempArray=paramHolidaysSaveVO.getDate().split("-");
        LambdaQueryWrapper<BasePersonInfo> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(BasePersonInfo::getUserno,paramHolidaysSaveVO.getLeaderCode());
        List<BasePersonInfo> personInfo = basePersonInfoRepository.list(wrapper);
        BeanUtils.copyProperties(paramHolidaysSaveVO,paramLeader);
        List<ParamLeader> paramLeaders=paramLeaderRepository.list(new LambdaQueryWrapper<ParamLeader>()
                .eq(ParamLeader::getLeaderCode,paramHolidaysSaveVO.getLeaderCode())
                .eq(ParamLeader::getDeptId,paramHolidaysSaveVO.getDeptId()));
        if(CollectionUtils.isEmpty(personInfo)){
            throw new Exception("未找到此工号对应领导信息");
        }
        List<ParamLeader> list=paramLeaderRepository.list(new LambdaQueryWrapper<ParamLeader>()
                .eq(ParamLeader::getLeaderName,paramHolidaysSaveVO.getLeaderName())
                .eq(ParamLeader::getDeptId,paramHolidaysSaveVO.getDeptId()));
            if(StringUtils.isEmpty(paramHolidaysSaveVO.getId())){
                if(!CollectionUtils.isEmpty(paramLeaders)){
                    throw new Exception("工号不可重复");
                }
                if(!CollectionUtils.isEmpty(list)){
                    if("1".equals(paramHolidaysSaveVO.getLeaderName())){
                        throw new Exception("只可设置一个带班关领导");
                    }
                    if("2".equals(paramHolidaysSaveVO.getLeaderName())){
                        throw new Exception("只可设置一个带班处领导");
                    }
                }
                for (BasePersonInfo basePersonInfo : personInfo) {
                    paramLeader.setLeaderId(basePersonInfo.getId());
                }
//                paramLeader.setSYear(Long.valueOf(tempArray[0]));
//                paramLeader.setSMonth(Long.valueOf(tempArray[1]));
                paramLeader.setCreateTime(LocalDateTime.now());
                paramLeader.setCreateBy(userInfo.getUserId());
                paramLeader.setUpdateBy(userInfo.getUserId());
                paramLeader.setUpdateTime(LocalDateTime.now());
                paramLeader.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                paramLeaderRepository.save(paramLeader);
        } else {
//                if("海关总署".equals(paramHolidaysSaveVO.getCustomName())){
                    ParamLeader byId = paramLeaderRepository.getById(paramHolidaysSaveVO.getId());
                    if(!paramHolidaysSaveVO.getLeaderName().equals(byId.getLeaderName())){
                        for (ParamLeader leader : list) {
                            if(paramHolidaysSaveVO.getLeaderName().equals(leader.getLeaderName())){
                                if("1".equals(paramHolidaysSaveVO.getLeaderName())){
                                    throw new Exception("只可设置一个带班关领导");
                                }
                            }
                        }
//                    }
                }
                if(!CollectionUtils.isEmpty(paramLeaders)){
                    throw new Exception("工号不可重复");
                }
              //  paramLeader.setSYear(Long.valueOf(tempArray[0]));
                paramLeader.setUpdateTime(LocalDateTime.now());
                paramLeader.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                paramLeader.setRecVersion(byId.getRecVersion());
                paramLeaderRepository.updateById(paramLeader);
            }
        return BaseResult.ok(paramLeader,"保存成功");
    }
}
